﻿// -----------------------------------------------------------------------
// <copyright file="RedirectHandler.cs" company="Microsoft">
// Handler for redirect server mode
// </copyright>
// -----------------------------------------------------------------------
namespace WebServer.BusinessLogic.Handlers
{
    using System;
    using System.IO;

    /// <summary>
    /// Class for process redirect mode
    /// </summary>
    class RedirectHandler:Handler
    {
        /// <summary>
        /// Redirecting to another server if content isn't found
        /// </summary>
        /// <param name="request">http request</param>
        public override Response Handle(Request request)
        {
            string filePath = request.HttpPath;

            if (!Configurator.Instance.RemoteServers.Contains("localhost:8081"))
            {
                Configurator.Instance.RemoteServers.Add("localhost:8081");
                ConfiguratorSerializer.Save();
                ConfiguratorSerializer.Load();
            }

            if (!File.Exists(filePath) && Configurator.Instance.ServerMode == ServerConfiguration.Redirect)  //checking existing file on local drive
            {
                
                foreach (string remoteserver in Configurator.Instance.RemoteServers)
                {
                    string urlToFile = remoteserver.TrimEnd(new[] { '/' }) + "/" + filePath.TrimStart(new[] { '/' });

                    urlToFile = !urlToFile.StartsWith("http", StringComparison.OrdinalIgnoreCase) ? "http://" + urlToFile : urlToFile;

                    Response remoteResponse = Communicator.Instance.GetPage(request, urlToFile);
                    if (remoteResponse.HttpResponseCode == 200)
                    {
                        var r = new Response();
                        // r.Data = Encoding.UTF8.GetBytes("Redirecting...");
                        r.SetRedirect(urlToFile);
                        return r;
                    }
                }
            }
            return this.NextHandler.Handle(request);
        }
    }
}
